package cn.tedu.d3_lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/*
ReentrantReadWriteLock 读写锁（乐观锁，无罪假设）
因此引入了ReentrantReadWriteLock，顾名思义，ReentrantReadWriteLock是Reentrant（可重入）Read（读）Write（写）Lock（锁），我们下面称它为读写锁。
读写锁内部又分为读锁和写锁，读锁可以在没有写锁的时候被多个线程同时持有，写锁是独占的。
读锁和写锁分离从而提升程序性能，读写锁主要应用于读多写少的场景。
 */
public class Lock {
    public static void main(String[] args) {
        Ticket target=new Ticket();
/*      Thread t=new Thread(target);
        Thread t1=new Thread(target);
        Thread t2=new Thread(target);
        t.start();t1.start();t2.start();*/

        //存放了四个线程的线程池
        ExecutorService pool= Executors.newFixedThreadPool(4);
        for (int i = 0; i <4; i++) {
            pool.execute(target);
        }
    }

}

class Ticket implements Runnable{

    static int ticket=100;

    //1.定义可重入读写锁对象,静态保证全局唯一
    static ReentrantReadWriteLock lock=new ReentrantReadWriteLock(true);

    @Override
    public void run() {

        while (true){
            //2.在操作共享资源前上锁
            lock.writeLock().lock();
            try {
                if(ticket>0){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " " + ticket--);
                }
                if (ticket <= 0) break;
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                //3.finally{}中释放锁,注意一定要手动释放,防止死锁,否则就独占报错了
                lock.writeLock().unlock();
            }
        }

    }
}
